﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using simFileWatch;
using System.Threading;

namespace eventDemo1
{
    public partial class Form1 : Form
    {
        private FileWatcher FileWatchEventSource;
        public Form1()
        {
            InitializeComponent();
            FileWatchEventSource = new FileWatcher(); //实例化FileWatcher对象；
            //将本地重载方法OnFileChange与事件相连接
            FileWatchEventSource.FileWatchEvent += new FileWatchEventHandler(OnFileChange);
        }

        protected delegate void addListboxItemCallBack(object sender, EventArgs e);
        private void OnFileChange(object Sender, EventArgs e)
        {
            //判断是否能当前线程调用
            if (listboxFileWatcher.InvokeRequired)
            {
                addListboxItemCallBack addListboxItemCall = new addListboxItemCallBack(OnFileChange);
                this.Invoke(addListboxItemCall, new object[] { this,EventArgs.Empty });
                return;
            }
            //记录下事件触发的历史记录
            listboxFileWatcher.Items.Add(DateTime.Now.ToString() + ": 文件发生改变.");
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void btnMinitor_Click(object sender, EventArgs e)
        {
            new Thread(() => FileWatchEventSource.MonitorFile()).Start();
        }
    }
}
